// pages/index/panel/purePanel/purePanel.js
import {
    Ble
} from "../../../../utils/ble.js"
import {
    Protocol
} from "../../../../utils/protocol"

Page({

    /**
     * Page initial data
     */
    data: {
        // for device
        bleStatus: "",
        macAddress: 0x00FFEECC,
        brightness: 0,
        tmpBrightness: 0, // 临时亮度
        lamp: false,

        // for page
        pageMargin: "10px",
        vH: "50vh",
        caculateStatus: false,
        btnTop: 0, // px
        btnBottom: 0, // px
        btnHeight: 0, // px
        proportion: 0,
        percent: "0%",

        // for preset
        presetList: [
            // {
            //     name: 'timer',
            //     icon: '/image/icon/countdown.png'
            // },
            // {
            //     name: '2',
            //     icon: ''
            // },
            // {
            //     name: '3',
            //     icon: ''
            // },
            // {
            //     name: '4',
            //     icon: ''
            // },
            {
                name: '50Brightness',
                presetBackground: '#343434',
                icon: '/image/icon/brightness_dim_50.png'
            },
            {
                name: '70Brightness',
                presetBackground: '#343434',
                icon: '/image/icon/brightness_dim_70.png'
            },
            {
                name: '100Brightness',
                presetBackground: '#343434',
                icon: '/image/icon/brightness_dim_100.png'
            },
            {
                name: 'nightMode',
                presetBackground: '#343434',
                icon: '/image/icon/brightness_b.png'
            },
        ],
    },

    /**
     * Lifecycle function--Called when page load
     */
    onLoad(options) {
        // 刷新 元素 状态
        // setInterval(() => {
        //     this.lampFresh()
        // }, 500);
    },

    /**
     * Lifecycle function--Called when page is initially rendered
     */
    onReady() {},

    /**
     * Lifecycle function--Called when page show
     */
    onShow() {

    },

    /**
     * Lifecycle function--Called when page hide
     */
    onHide() {

    },

    /**
     * Lifecycle function--Called when page unload
     */
    onUnload() {

    },

    /**
     * Page event handler function--Called when user drop down
     */
    onPullDownRefresh() {

    },

    /**
     * Called when page reach bottom
     */
    onReachBottom() {

    },

    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage() {

    },
    // ================================================ 蓝牙通信相关 ==================================================
    /**
     * 蓝牙通信方法
     * @param {string} bytes 
     */
    sendData(bytes) {
        Ble.server.startAdvertising({
            advertiseRequest: {
                serviceUuids: bytes
            },
            powerLevel: 'high',
            success: (res) => {
                console.log(" advertise message success ")
                this.timer = setTimeout(() => {
                    Ble.server.stopAdvertising({})
                }, 300)
            },
            fail: (error) => {
                console.log(JSON.stringify(error))
            },
            complete: () => {
                console.log(" advertise message complete ")
            }
        })
    },
    /**
     * 配对
     */
    pairDevice(e) {
        let params = new Uint8Array(9)
        params[0] = 0x01
        params[3] = 0xFF
        params[4] = 0xEE
        params[5] = 0xCC
        params[6] = 0xFF
        params[7] = 0xEE
        params[8] = 0xCC
        let bytes = Protocol.encode(0x02, this.data.macAddress, params)
        this.sendData(bytes)
    },
    /**
     * 仅开灯，保留原色温和亮度
     */
    turnOn(e) {
        let params = new Uint8Array(9)
        params[0] = 0x23
        let bytes = Protocol.encode(0x3B, this.data.macAddress, params)
        this.sendData(bytes)
    },
    /**
     * 仅关灯，保留原色温和亮度
     */
    turnOff(e) {
        let params = new Uint8Array(9)
        params[0] = 0x24
        let bytes = Protocol.encode(0x3B, this.data.macAddress, params)
        this.sendData(bytes)
    },
    /**
     * 单独修改亮度，保持原色温
     * @param {Number} tmpBrightness 
     * 亮度值 范围0-100，对应亮度0x00~0x64
     */
    setBrightness(tmpBrightness) {
        // 亮度数值范围判断
        // if (tmpBrightness > 100) {
        //     tmpBrightness = 100
        // } else if (tmpBrightness < 0) {
        //     tmpBrightness = 0
        // }
        this.setData({
            brightness: tmpBrightness
        })
        this.lampFresh()
        let params = new Uint8Array(9)
        params[0] = 0x01
        params[5] = this.data.brightness // 设置亮度0x00~0x64 等于10进制的0~100（js自动转换）
        params[7] = 0x03
        let bytes = Protocol.encode(0x3B, this.data.macAddress, params)
        this.sendData(bytes)
    },
    /**
     * 预设：修改色温和亮度
     * @param {Number} tmpCW 
     * @param {Number} tmpBrightness
     * tmpCW 为色温值，tmpBrightness 为亮度值，范围均为 0-100
     * 对应0x00~0x64
     */
    // presetCCT(tmpCW, tmpBrightness) {
    //     this.setData({
    //         cw: tmpCW,
    //         brightness: tmpBrightness
    //     })
    //     let params = new Uint8Array(9)
    //     params[0] = 0xB1
    //     params[4] = tmpCW // 设置色温0x00~0x64 等于10进制的0~100（js自动转换）
    //     params[5] = tmpBrightness // 设置亮度0x00~0x64 等于10进制的0~100（js自动转换）
    //     params[7] = 0x03
    //     let bytes = Protocol.encode(0x3B, this.data.macAddress, params)
    //     this.sendData(bytes)
    // },
    //================================================ 页面处理 方法 ================================================
    /**
     * 滑块首次触摸的事件
     */
    setY(e) {
        if (this.data.caculateStatus == false) {
            var vTop = e.currentTarget.offsetTop
            var vHeight = wx.getWindowInfo().windowHeight * (this.data.vH.slice(0, this.data.vH.length - 2) / 100)
            var vBottom = vTop + vHeight
            var oneHeight = Math.trunc(vHeight / 100)
            this.setData({
                // 计算完成标志为 成功
                caculateStatus: true,
                // 按钮头顶 y坐标
                btnTop: vTop,
                // 按钮底部 y坐标
                btnBottom: vBottom,
                // 得出按钮 高度总坐标
                btnHeight: vHeight,
                // 得出按钮 1% 高度
                proportion: oneHeight
            })
            console.log("caculate ok !")
        }
        // console.log("minTop: " + vTop + ",maxTop: " + vBottom)
        // console.log("f: " + e.touches[0].pageY)
    },
    /**
     * 滑块设置亮度
     */
    selectBrightness(e) {
        // 滑动产生新的 y坐标 0 ~ btnHeight
        var newY = e.touches[0].pageY
        var minTop = this.data.btnTop - 10
        var maxTop = this.data.btnBottom + 1
        var touchValue = 0
        if (newY >= minTop && newY <= maxTop) {
            // 取整
            touchValue = Math.trunc((maxTop - newY) / this.data.proportion)
            if (touchValue <= 100) {
                this.setData({
                    brightness: touchValue,
                    percent: touchValue + '%'
                })
            } else {
                this.setData({
                    brightness: 100,
                    percent: 100 + '%'
                })
            }
        }
        setTimeout(() => {
            console.log("setBrightness ok !")
            this.setBrightness(this.data.brightness)
        }, 800);
    },
    /**
     * 开关状态监听，控制灯开关，适配预设按钮和亮度滑块的联动
     */
    listenerSwitch(e) {
        // console.log('switch当前状态: ', e.detail.value);
        if (e.detail.value == true) {
            if (this.data.tmpBrightness == 0) {
                this.setData({
                    brightness: 100,
                    lamp: true
                })
            } else {
                this.setData({
                    brightness: this.data.tmpBrightness,
                    lamp: true
                })
            }
            this.lampFresh()
            console.log("lamp on ok !")
            this.turnOn()
        } else {
            this.resetPresetBackground()
            if (this.data.brightness == 0) {
                this.setData({
                    lamp: false
                })
            } else {
                this.setData({
                    tmpBrightness: this.data.brightness,
                    brightness: 0,
                    lamp: false
                })
                this.lampFresh()
            }
            console.log("lamp off ok !")
            this.turnOff()
        }
    },
    /**
     * 预设按钮、灯开关、滑块等元素 间的状态同步
     */
    lampFresh() {
        if (this.data.brightness > 0) {
            this.setData({
                lamp: true,
                percent: this.data.brightness + "%"
            })
        } else {
            this.setData({
                lamp: false,
                percent: "0%"
            })
        }
    },
    /**
     * 改变按钮背景色，id 为按钮字符
     * @param {String} id 
     */
    resetPresetBackground(id) {
        // 清空所有按钮背景，调用即执行
        for (let i = 0; i < this.data.presetList.length; i++) {
            let tmp = 'presetList[' + i + '].presetBackground'
            this.setData({
                [tmp]: "#343434",
            })
        }
        // 重新更新id对应按钮的背景，无参传入不执行
        if (id != null) {
            let tmpColor = 'presetList[' + id + '].presetBackground'
            this.setData({
                [tmpColor]: "#03A9F4",
            })
        }
    },
    /**
     * 预设按钮快捷控制
     */
    presetControl(e) {
        // 50 70 100 10 percent brightness
        switch (e.currentTarget.id) {
            case "50Brightness":
                this.resetPresetBackground(e.currentTarget.dataset.index)
                // 设置暖色 最亮
                this.setBrightness(50)

                break;

            case "70Brightness":
                this.resetPresetBackground(e.currentTarget.dataset.index)
                // 设置70% 亮度
                this.setBrightness(70)

                break;

            case "100Brightness":
                this.resetPresetBackground(e.currentTarget.dataset.index)
                // 设置100% 亮度
                this.setBrightness(100)

                break;

            case "nightMode":
                this.resetPresetBackground(e.currentTarget.dataset.index)
                // 设置10% 亮度
                this.setBrightness(10)

                break;

            default:
                break;
        }
    },
})